package cn.ricecode.mybatis.util;


import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class ZipUtils {


    /**
     * 文件压缩
     *
     * @param filename 文件名称
     * @param files    文件列表
     * @return 压缩文件1
     */
    public static File zipFiles(String filename, List<File> files) {
        try {
            if (files.isEmpty()) {
                //如果为空的放入提示文件
                File file = File.createTempFile("README", ".txt");
                org.apache.commons.io.FileUtils.writeStringToFile(file, "该批量的用处没有人上传身份证照片", StandardCharsets.UTF_8);
                files.add(file);
            }
        }catch (Exception e){
            log.info("增加空文件提示失败",e);
        }

        File zipFile = new File("C:\\Users\\liuzlan\\Desktop\\1.zip");
        if(!zipFile.exists()){
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                log.info("{}",e);
            }
        }
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile), StandardCharsets.UTF_8)) {
            files.forEach(file -> {
                try {
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    zipOutputStream.putNextEntry(zipEntry);
                    zipOutputStream.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
                } catch (Exception e) {
                    log.warn("putNextEntry: {} error ", file.getName());
                }
            });
        } catch (Exception e) {
            log.warn("zipFiles: {} error ", filename);
        }
        return zipFile;
    }
}
